package com.yin.myproject.zk.selector;

import com.yin.myproject.zk.client.ZkClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Eason on 2017/8/7.
 */
public class MasterSelector implements Runnable {

    final String ROOT_PATH = "/task/node";

    private CuratorFramework client;
    private String path;
    private String name;

    public MasterSelector(CuratorFramework client, String path, String name) {
        this.client = client;
        this.path = path;
        this.name = name;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("创建ZK客户端1");
        CuratorFramework zkClient1 = ZkClient.getNewZkClient();
        System.out.println("创建ZK客户端2");
        CuratorFramework zkClient3 = ZkClient.getNewZkClient();
        System.out.println("创建ZK客户端3");
        CuratorFramework zkClient2 = ZkClient.getNewZkClient();
        zkClient1.start();
        zkClient2.start();
        zkClient3.start();
        System.out.println("client1创建节点数据");
        zkClient1.create().withMode(CreateMode.EPHEMERAL).forPath("/task/node/192.168.0.1");
        System.out.println("client2创建节点数据");
        zkClient2.create().withMode(CreateMode.EPHEMERAL).forPath("/task/node/192.168.0.2");
        System.out.println("client3创建节点数据");
        zkClient3.create().withMode(CreateMode.EPHEMERAL).forPath("/task/node/192.168.0.3");
        ExecutorService service = Executors.newFixedThreadPool(3);
        service.execute(new MasterSelector(zkClient1, "/task/master", "节点一"));
        service.execute(new MasterSelector(zkClient2, "/task/master", "节点二"));
        service.execute(new MasterSelector(zkClient3, "/task/master", "节点三"));
        while (true) {
        }
    }

    /**
     * 测试主节点选举
     */
    @Override
    public void run() {
        MasterSelectorExample example = new MasterSelectorExample(client, path, name);
        try {
            example.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

